package top.ztf.erp.filter;

import top.ztf.erp.domain.User;
import top.ztf.erp.service.UserService;
import top.ztf.erp.service.imp.UserServiceImp;
import top.ztf.erp.utils.ResponseClient;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

@WebFilter({"/user/*","/role/*","/permission/*","/common/*"})
public class AuthFilter implements Filter {



    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String requestURI = request.getRequestURI();
        String method = request.getParameter("method");

        // 放行登录的请求
        if (requestURI.contains("login.jsp") || "login".equals(method) || requestURI.equals("/erp/")){
            chain.doFilter(req, resp);
            return;
        }

        // 判断登录条件
        HttpSession session = request.getSession();
        Object object = session.getAttribute("user");
        if (object==null){
            // 未登录 无法访问,跳转 login.jsp
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }

        // 登录后才能访问main.jsp
        if (method.equals("main")){
            chain.doFilter(req, resp);
            return;
        }

        User user = (User) object;


        // 暂时缓存起来
        String permission =null;
        if (session.getAttribute("auth")==null){
            UserService userService = new UserServiceImp();
            permission = userService.getPermissionByButton(user).toString();
            session.setAttribute("auth",permission);
        }else {
            permission = (String) session.getAttribute("auth");
        }


        // 拼接操作url
        String s = requestURI.substring(5);
        String uri = s+"?method="+method;

        if (permission.contains(uri)){
            // 有权限,允许访问
            chain.doFilter(req, resp);
        }else {
            // 无权限 访问
            response.setContentType("text/html;charset=utf-8");
            ResponseClient.fail("无权访问,请联系管理员",response);
        }

    }

    public void init(FilterConfig config) throws ServletException {


    }

}
